package king.dominic.jlibrary.util;

import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;

import king.dominic.jlibrary.view.WindowUtil;

/**
 * Created by Administrator on 2017/10/14.
 */

public class AndroidBug5497Workaround {
    private final int mStatusBar;
    private final int mActionBar;
    private boolean isStatusBar = false;

    // For more information, see https://code.google.com/p/android/issues/detail?id=5497
    // To use this class, simply invoke assistActivity() on an Activity that already has its content view set.

    public static void assistActivity(AppCompatActivity activity, int statusBar, int actionBar) {
         new AndroidBug5497Workaround(activity, statusBar, actionBar);
    }

    public static void assistActivity(AppCompatActivity activity) {
        assistActivity(activity,WindowUtil.getStatusBarHeightDefault(activity),0);
    }

    private View mChildOfContent;
    private int usableHeightPrevious;
    private FrameLayout.LayoutParams frameLayoutParams;

    private AndroidBug5497Workaround(AppCompatActivity activity, int statusBar, int actionBar) {
        ViewGroup content = WindowUtil.getViewRoot(activity);
        mStatusBar = statusBar;
        mActionBar = actionBar;
        mChildOfContent = content.getChildAt(0);
        mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                possiblyResizeChildOfContent();
            }
        });
        frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
    }

    private void possiblyResizeChildOfContent() {
        final int windowHeight = computeUsableHeight();
        if (windowHeight == WindowUtil.height) isStatusBar = true;
        final int usableHeightNow = windowHeight - mActionBar/* - (isStatusBar ? mStatusBar : 0)*/+mStatusBar;
        if (usableHeightNow != usableHeightPrevious) {
            frameLayoutParams.height = usableHeightNow;
            mChildOfContent.requestLayout();
            usableHeightPrevious = usableHeightNow;
        }
    }

    private int computeUsableHeight() {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);
        return (r.bottom - r.top);
    }

}
